﻿using System.Collections.Generic;
using System.Text;
using Medianamik.Core.DAL.SQL;

namespace Medianamik.Core.DAL
{
    public class InsertNodePropertyValueCommandBuilder
    {

        private readonly ParameterNameGenerator _paramGenerator = new ParameterNameGenerator();

        protected SubSonic.DataProvider Provider
        {
            get;
            private set;
        }

        protected NodeProperty NodeProperty
        {
            get;
            private set;
        }

        public InsertNodePropertyValueCommandBuilder(SubSonic.DataProvider pSubsonicDataProvider, NodeProperty pProperty)
        {
            Provider = pSubsonicDataProvider;
            NodeProperty = pProperty;
        }


        public SubSonic.QueryCommand Build()
        {
            var queryParams = new List<IParameter>();

            var npvTable = new NodePropertyValueTable("npv");

            var columnValues = new Dictionary<Column, IExpression>();

            var nodeIdParam = new Parameter(_paramGenerator.Next(), NodeProperty.Node.ID);
            queryParams.Add(nodeIdParam);
            columnValues.Add(npvTable["NodeId"], new ParameterExpression(nodeIdParam));

            var propertyIdParam = new Parameter(_paramGenerator.Next(), NodeProperty.NodeTypePropertyID);
            queryParams.Add(propertyIdParam);
            columnValues.Add(npvTable["PropertyId"], new ParameterExpression(propertyIdParam));

            var valueParam = new Parameter(_paramGenerator.Next(), NodeProperty.Value);
            queryParams.Add(valueParam);
            columnValues.Add(npvTable["Value"], new ParameterExpression(valueParam));

            var revisionParam = new Parameter(_paramGenerator.Next(), NodeProperty.Revision);
            queryParams.Add(revisionParam);
            columnValues.Add(npvTable["Revision"], new ParameterExpression(revisionParam));

            var cultureParam = new Parameter(_paramGenerator.Next(), NodeProperty.Culture.Name);
            queryParams.Add(cultureParam);
            columnValues.Add(npvTable["CultureName"], new ParameterExpression(cultureParam));


            var insertClause = new InsertClause(columnValues);

            var finalQuery = new StringBuilder()
                .Append(insertClause.ToSQL())
                .AppendLine(" SELECT SCOPE_IDENTITY() ");

            var command = new SubSonic.QueryCommand(finalQuery.ToString(), Provider.Name);

            foreach (var p in queryParams)
            {
                if (p.Name == "@p3")
                    command.Parameters.Add(p.Name, p.Value, System.Data.DbType.String);
                else
                    command.Parameters.Add(p.Name, p.Value);
            }

            return command;
        }
    }
}
